package com.xxx.service.impl;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.xxx.common.IdWorkerManage;
import com.xxx.common.dto.Page;
import com.xxx.common.dto.Pagination;
import com.xxx.dao.SysUserRoleDao;
import com.xxx.model.SysUserRole;
import com.xxx.service.SysUserRoleService;

@Service
public class SysUserRoleServiceImpl implements SysUserRoleService {
	
	@Autowired
	private SysUserRoleDao sysUserRoleDao;
	
	@Override
	@Transactional
	public long saveOrUpdate(SysUserRole sysUserRole) throws Exception {
		if(sysUserRole.getId() == null){
			sysUserRole.setId(IdWorkerManage.getId());
			return sysUserRoleDao.save(sysUserRole);
		}
		return sysUserRoleDao.update(sysUserRole);
	}

	@Override
	@Transactional
	public boolean delete(long id) throws Exception{
		return sysUserRoleDao.delete(id);
	}

	@Override
	public SysUserRole getEntity(long id) throws Exception{
		return sysUserRoleDao.getEntity(id);
	}

	@Override
	public int getCount(Map<String, Object> whereMap) {
		return sysUserRoleDao.getCount(whereMap);
	}
	
	@Override
	public List<SysUserRole> getList(Map<String, Object> whereMap) {
		return sysUserRoleDao.getList(whereMap);
	}

	@Override
	public List<SysUserRole> getList(Map<String, Object> whereMap, Pagination pagination) {
		return sysUserRoleDao.getList(whereMap, pagination);
	}
	
	@Override
	public Page<SysUserRole> getPage(Map<String, Object> whereMap, Pagination pagination) {
		int count = this.getCount(whereMap);
		if(count > 0){
			List<SysUserRole> list = this.getList(whereMap, pagination);
			return new Page<SysUserRole>(pagination.getCurrentPage(), pagination.getPageSize(), count, list);
		}
		return new Page<SysUserRole>(pagination.getCurrentPage(), count);
	}

	@Override
	public Map<Long, Long> getUserRoleMap(long userid) throws Exception {
		Map<String, Object> whereMap = new HashMap<>();
		whereMap.put("userid", userid);
		List<SysUserRole> list = this.getList(whereMap);
		Map<Long,Long> map = new HashMap<>();
		for (SysUserRole sys_RoleUser : list) {
			map.put(sys_RoleUser.getRoleid(),sys_RoleUser.getId());
		}
		return map;
	}

	@Override
	public Set<Long> getUserRoleSet(long userid) {
		Map<String, Object> whereMap = new HashMap<>();
		whereMap.put("userid", userid);
		List<SysUserRole> list = this.getList(whereMap);
		Set<Long> roleSet = new HashSet<>();
		for (SysUserRole sysUserRole : list) {
			roleSet.add(sysUserRole.getRoleid());
		}
		return roleSet;
	}
}
